package com.yimi.yinhepda.views.login.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.pda.uce.commom.pickerview.builder.OptionsPickerBuilder;
import com.pda.uce.commom.pickerview.listener.OnOptionsSelectListener;
import com.pda.uce.commom.pickerview.view.OptionsPickerView;
import com.pda.uce.commom.util.AppUtil;
import com.pda.uce.commom.util.InputMethodUtils;
import com.pda.uce.commom.util.LoadUtils;
import com.pda.uce.commom.util.LogUtil;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.callbacks.UICallBack;
import com.pda.ym.updateApk.UpdateApk;
import com.pda.ym.utils.ActivityStack;
import com.pda.ym.utils.AppInfoHelper;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.FastClick;
import com.pda.ym.utils.NetworkUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SysInfo;
import com.pda.ym.utils.SystemEnvironment;
import com.uce.pda.MyAppLication;
import com.uce.pda.module.ConnectionResultLister;
import com.uce.pda.module.LoginActivityModule;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.base.BaseActivity2;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.dao.DepartmentTableDao;
import com.yimi.yinhepda.db.dao.UserInfoTableDao;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.helper.DbHelperUC;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.yimi.yinhepda.db.table.UserInfoTable;
import com.yimi.yinhepda.utils.ActivityStack2;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.ExitDialog;
import com.yimi.yinhepda.utils.GzipUtil;
import com.yimi.yinhepda.utils.ToastUtil;
import com.yimi.yinhepda.views.break_card.BreadCardActivity;
import com.yimi.yinhepda.views.login.contract.LoginContract;
import com.yimi.yinhepda.views.login.model.CompanyFindAllInfo;
import com.yimi.yinhepda.views.login.presenter.LoginPresenter;
import com.yimi.yinhepda.views.login.util.LoginUtil;
import com.yimi.yinhepda.views.main.NewMainActivity;
import com.yimi.yinhepda.views.offline.OffLineOperatorListActivity;
import com.yimi.yinhepda.views.setting_module.SettingActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author 000432
 */
@Route(path = Constants.YM_LOGIN_ACTIVITY)
public class LoginActivity extends BaseActivity2<LoginContract.LoginView, LoginContract.LoginBiz, LoginPresenter>
        implements LoginContract.LoginView, View.OnLayoutChangeListener, CompoundButton.OnCheckedChangeListener {

    /**
     * 设置公司和服务器的请求回调值
     */
    public static final int LOGIN_REQUEST_CODE = 100;
    /**
     * 请求APK安装权限
     */
    public static final int RQUEST_INSTALL_PACKAGES = 103;
    /**
     * 滚动View
     */
    @Bind(R.id.sv_rootLayout)
    ScrollView mScrollView;
    @Bind(R.id.cb_password)
    CheckBox cbPassword;
    @Bind(R.id.tv_companyname)
    TextView companyName;
    @Bind(R.id.et_username)
    TextView empCode;
    @Bind(R.id.et_pwd)
    EditText password;
    @Bind(R.id.tv_version)
    TextView tvVersion;
    @Bind(R.id.cb_offlineModel)
    CheckBox cbOfflineModel;
    /**
     * 验证码 线性布局
     */
    @Bind(R.id.ll_captcha)
    LinearLayout llCaptcha;
    @Bind(R.id.et_captcha)
    EditText etCaptcha;
    @Bind(R.id.iv_captcha)
    ImageView ivCaptcha;

    @Bind(R.id.radio_kuaiyun_login)
    Button radioKuaiyunLogin;
    @Bind(R.id.radio_kuaidi_login)
    Button radioKuaidiLogin;
    @Bind(R.id.include_layout_kuaiyun)
    LinearLayout includeLayoutKuaiyun;
    @Bind(R.id.include_layout_kuaidi)
    RelativeLayout includeLayoutKuaidi;
    @Bind(R.id.kuaiyun_img_five)
    ImageView kuaiyunImgFive;
    /**
     * 软件盘弹起后所占高度阀值
     */
    private int keyHeight = 0;
    /**
     * 上一次的屏幕底部尺寸
     */
    private int mOldBottom = 0;
    /**
     * ScrollView的子布局
     */
    private LinearLayout mChildLayout;
    /**
     * 软键盘弹出所需变量
     */
    private View activityRootView;
    /**
     * 公司名称集合
     */
    private int isCompanyOptions1;
    private CompanyFindAllInfo mCompanyInfo;

    LoginActivityModule loginActivityModule;

    boolean dismiss = false;//隐藏

    @Override
    public LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    public String getPageName() {
        return "登录界面";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        loginActivityModule = new LoginActivityModule();
        loginActivityModule.initAsertDb();
        ButterKnife.bind(this);
        init();

        radioKuaiyunLogin.setActivated(true);
        EventBus.getDefault().register(this);

    }


    private void init() {
        llCaptcha.setVisibility(View.GONE);
        cbOfflineModel.setChecked(false);
        cbOfflineModel.setOnCheckedChangeListener(this);
        //硬件标识权限请求
        mT.requestHardwareFlagPermission();

        sharedPreferUtil.setBooleanValue(Common.PDT_DEV, false);
        // 软键盘弹出所需变量
        activityRootView = findViewById(R.id.sv_rootLayout);
        //获取屏幕高度
        /* 屏幕高度 */
        int screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        mChildLayout = (LinearLayout) findViewById(R.id.child_layout);

        companyName.setText(sharedPreferUtil.getCompanyName());
        empCode.setText(sharedPreferUtil.getWorkNum());
        password.setText(sharedPreferUtil.getPwd());
        if (sharedPreferUtil.getRememberPassword()) {
            cbPassword.setChecked(true);
        } else {
            cbPassword.setChecked(false);
        }

        //首次显示更新内容
        showUpdateInfo();

        //设置版本号
        sharedPreferUtil.setValue(Constants.VERSION, AppInfoHelper.getAppVersion(this) + "");
        //初始化系统信息类
        SysInfo.getInstance().init(this);
        LogUtil.e("onCreate-------: density="
                + SysInfo.getInstance().getDensity()
                + ",dpi=" + SysInfo.getInstance().getDensityDpi()
                + ",px=" + SysInfo.getInstance().getPixel());

        initView();
    }

    private void initView() {
        kuaiyunImgFive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(password.getText().toString().trim())) {
                    if (dismiss) {
                        dismiss = false;
                        kuaiyunImgFive.setImageResource(R.mipmap.openeye);
                        password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    } else {
                        dismiss = true;
                        kuaiyunImgFive.setImageResource(R.mipmap.closeeye);
                        password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                    password.setSelection(password.getText().toString().trim().length());
                    InputMethodUtils.showSoftInput(password);
                }
            }
        });
    }


    /**
     * 首次显示更新内容
     */
    private void showUpdateInfo() {
        //旧版本号
        int oldVersion;
        try {
            oldVersion = Integer.parseInt(sharedPreferUtil.getValue(Constants.VERSION));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            oldVersion = 0;
        }
        //当前版本号
        int currVersion = AppInfoHelper.getAppVersion(this);
        if (currVersion > oldVersion) {
            StringBuilder stringBuilder = new StringBuilder();
            try {
                BufferedReader bf = new BufferedReader(new InputStreamReader(getAssets().open("updateInfo"), "UTF-8"));
                String line;
                while ((line = bf.readLine()) != null) {
                    stringBuilder.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //添加版本名称
            PackageManager manager = getPackageManager();
            PackageInfo info;
            try {
                info = manager.getPackageInfo(getPackageName(), 0);
                if (info != null) {
                    stringBuilder.append("更新后版本号：" + info.versionName);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            MyDialog.showAlertDialog(this, "提示", stringBuilder.toString(), R.color.black, "知道了", false);

            //删除上一个版本残留的快递路由db文件
            File file = new File(DbHelperUC.DB_PATH, DbHelperUC.DB_NAME);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (SharedPreferUtil.getInstance().getIntValue(Constants.LOGIN_TYPE) == 2) {
            initLoginKuaidi();
        } else {
            initLoginKuaiYun();
        }

//        mT.requestInstallPackages();

        //校验设备型号
        String phoneModel = SysInfo.getInstance().getPhoneModel();
        if (phoneModel != null) {
            if (phoneModel.equals(Common.DEV_MODEL)) {
                //横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //android6.0开始权限申请
            int permission = ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permission == PackageManager.PERMISSION_GRANTED) {
                //检测更新版本
                UpdateApk.getInstance(getContext(), sharedPreferUtil).upgrade();
            }
        } else {
            //检测更新版本
            UpdateApk.getInstance(getContext(), sharedPreferUtil).upgrade();
        }

        activityRootView.addOnLayoutChangeListener(this);
        //清空分拣票数
        sharedPreferUtil.setValue(Common.COOKIE, "");
        sharedPreferUtil.setSortingTotalBill("0");

        loginActivityModule.out();

        tvVersion.setText(String.format("%s版本号：%s", SystemEnvironment.getEnvShortName(Constants.getServerIp()), AppInfoHelper.getAppVersionName(this)));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ActivityStack.getInstance().exit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LOGIN_REQUEST_CODE:
                    companyName.setText(sharedPreferUtil.getCompanyName());
                    break;
                default:
                    break;
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case RQUEST_INSTALL_PACKAGES:
                //安装APK请求权限
                if ((grantResults.length > 0) && (grantResults[0] != PackageManager.PERMISSION_GRANTED)) {
                    ActivityCompat.requestPermissions((Activity) getContext(),
                            new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
                            LoginActivity.RQUEST_INSTALL_PACKAGES);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 点击事件
     */
    @OnClick({R.id.btn_login, R.id.ll_companyQuery, R.id.img_setting, R.id.iv_captcha, R.id.ll_uc_express, R.id.radio_kuaiyun_login, R.id.radio_kuaidi_login})
    public void onClick(View v) {
        if (FastClick.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.img_setting:
                //log图片链接系统设置
                toActivity(SettingActivity.class);
                break;
            case R.id.ll_companyQuery:
                //查询公司名称
                LoadUtils.showLoading("正在查询企业...", getContext());
                mT.getLogic().queryCompany();
                break;
            case R.id.btn_login:
                SharedPreferUtil.getInstance().setIntValue(Constants.LOGIN_TYPE, 1);
////                //模拟快递登录
//                new UcLoginUtil().loginHttp(this, "022375", "Uc112233", new UICallBack() {
//                    @Override
//                    public void onError(String msg) {
//                    }
//
//                    @Override
//                    public void onSuccess(Object obj) {
//
//                    }
//                });
                String mCompanyCode = sharedPreferUtil.getCompanyCode();
                loginActivityModule.loginHttp(empCode.getText().toString()+"@"+mCompanyCode, AppUtil.getMD5Str(password.getText().toString().trim()), LoginActivity.this, new ConnectionResultLister<String>() {
                    @Override
                    public void getResult(int errorCode, String objects) {
                        if (errorCode == 0) {

                        }
                    }
                });
                loginActivityModule.loginHttp(empCode.getText().toString(), AppUtil.getMD5Str(password.getText().toString().trim()), LoginActivity.this, new ConnectionResultLister<String>() {
                    @Override
                    public void getResult(int errorCode, String objects) {
                        if (errorCode == 0) {

                        }
                    }
                });
                //校验网络时间成功后，则登录
                checkNetworkTime();
                break;
            case R.id.iv_captcha:
                //点击重新获取验证码
                getCaptchaImage();
                break;
//            case R.id.ll_uc_express:
//                Common.goToUCApp(this);
//                break;
            case R.id.radio_kuaidi_login:
                initLoginKuaidi();
                break;
            case R.id.radio_kuaiyun_login:
                initLoginKuaiYun();
                break;
            default:
                break;
        }
    }

    /****
     * 初始化快递登录
     */
    private void initLoginKuaidi() {
        includeLayoutKuaidi.setVisibility(View.VISIBLE);
        includeLayoutKuaiyun.setVisibility(View.GONE);
        loginActivityModule.initView(getWindow().getDecorView());
        loginActivityModule.oncreate(LoginActivity.this);
        radioKuaidiLogin.setActivated(true);
        radioKuaiyunLogin.setActivated(false);
        SharedPreferUtil.getInstance().setIntValue(Constants.LOGIN_TYPE, 2);
    }

    /****
     * 初始化快运登录
     */
    private void initLoginKuaiYun() {
        includeLayoutKuaiyun.setVisibility(View.VISIBLE);
        includeLayoutKuaidi.setVisibility(View.GONE);
        radioKuaidiLogin.setActivated(false);
        radioKuaiyunLogin.setActivated(true);
        SharedPreferUtil.getInstance().setIntValue(Constants.LOGIN_TYPE, 1);
    }


    private void selectCompany(final List<CompanyFindAllInfo> companyInfos) {
        OptionsPickerView problemOptions = new OptionsPickerBuilder(getContext(),
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        isCompanyOptions1 = options1;
                        mCompanyInfo = companyInfos.get(options1);
                        companyName.setText(mCompanyInfo.getShortName());
                        sharedPreferUtil.setCompanyCode(mCompanyInfo.getCompCode());
                        sharedPreferUtil.setCompanyName(mCompanyInfo.getShortName());
                    }
                })
                .setTitleText("选择企业")
                //确定按钮文字
                .setSubmitText("确定")
                //取消按钮文字
                .setCancelText("取消")
                //确定按钮文字颜色
                .setSubmitColor(Color.BLACK)
                //取消按钮文字颜色
                .setCancelColor(Color.BLACK)
                //滚轮文字大小
                .setContentTextSize(20)
                //循环与否
                .setCyclic(false, false, false)
                //设置默认选中项
                .setSelectOptions(isCompanyOptions1)
                //是否显示为对话框样式
                .isDialog(false)
                .build();
        problemOptions.setPicker(companyInfos);
        problemOptions.show();
    }

    /**
     * 校验网络时间
     */
    @Override
    public void checkNetworkTime() {
        //校验设备编码
        //String imei = SysInfo.getInstance().getImei();
        //if (imei == null || imei.equals("")) {
        //  showToast("无法获取设备编码，不可登录！");
        //  return;
        //}
        //获取设备型号
        String phoneModel = SysInfo.getInstance().getPhoneModel();
        if (phoneModel == null || phoneModel.equals("")) {
            showToast("无法获取到设备型号，不可登录！");
            return;
        }

        final String mCompanyCode = sharedPreferUtil.getCompanyCode();
        final String mEmpCode = empCode.getText().toString().trim();
        final String mPwd = password.getText().toString().trim();
        if (TextUtils.isEmpty(mEmpCode) || TextUtils.isEmpty(mPwd)) {
            MyDialog.showAlertDialog(this, "用户名或密码不能为空");
        } else if (llCaptcha.getVisibility() == View.VISIBLE && TextUtils.isEmpty(etCaptcha.getText().toString())) {
            showToast("请输入验证码！");
        } else if (TextUtils.isEmpty(mCompanyCode)) {
            MyDialog.showAlertDialog(this, "公司代码未设置");
        } else {
            /******无网时离线登录******/
            if (!NetworkUtil.isConnect(BaseApplication.getContext()) || cbOfflineModel.isChecked()) {
                //获取设备型号（用户G7打开）,用于平板打卡机，不可离线登录
                if (phoneModel.equals(Common.DEV_MODEL)) {
                    showToast("请检查网络连接！");
                    return;
                }

                if (sharedPreferUtil.getWorkNum().equals("")) {
                    if (cbOfflineModel.isChecked()) {
                        showToast("首次不可离线登录！");
                    } else {
                        //没有保存工号，是首次登录，且没有网络则提示
                        showToast("请检查网络连接！");
                    }
                    return;
                }
                MyDialog dialog = new MyDialog(this);
                dialog.setIcon(R.drawable.alert);
                String message;
                if (cbOfflineModel.isChecked()) {
                    message = "是否离线登录？";
                } else {
                    message = "当前没有网络\n是否离线登录？";
                }
                dialog.setMessage(message);
                dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UserInfoTable userInfoTable = new UserInfoTableDao().getDataByWorkNum(mEmpCode);
                        if (userInfoTable == null) {
                            //工号不存在当前部门，不能登录
                            showToast("离线模式：当前部门工号不存在，不可登录！");
                            return;
                        }

                        dialog.dismiss();
                        if (cbPassword.isChecked()) {
                            sharedPreferUtil.setRememberPassword(true);
                        } else {
                            password.setText("");
                            sharedPreferUtil.setRememberPassword(false);
                        }
                        //设置为离线模式
                        sharedPreferUtil.setOfflineMode(true);
                        //跳转至离线操作界面
                        toActivity(OffLineOperatorListActivity.class);
                    }
                });
                dialog.setNegativeClickListener(R.drawable.btn_cancel_selector, "否", null);
                dialog.setCancelable(false);
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                return;
            }
            /******无网时离线登录******/

            //设置为非离线模式
            sharedPreferUtil.setOfflineMode(false);

            /****校验服务端时间成功后则请求登录****/
            boolean needVcode = false;
            if (llCaptcha.getVisibility() == View.VISIBLE) {
                needVcode = true;
            }
            mT.checkNetworkTime(mCompanyCode, mEmpCode, mPwd, etCaptcha.getText().toString(), needVcode);
        }
    }

    @Override
    public void loginSuccess(final String pwd) {
        if (cbPassword.isChecked()) {
            sharedPreferUtil.setPassword(pwd);
            sharedPreferUtil.setRememberPassword(true);
        } else {
            password.setText("");
            sharedPreferUtil.setPassword("");
            sharedPreferUtil.setRememberPassword(false);
        }

        if (sharedPreferUtil.getServerIpHaveChanged()) {
            //环境发生变化
            if (sharedPreferUtil.getServerIp().equals(SystemEnvironment.LTLPlatformIp)
                    || sharedPreferUtil.getServerIp().equals(SystemEnvironment.YhGrayPlateformIp)) {
                //环境切换为正式环境时，copyDB文件
                getDBFile();
            } else {
                //其他环境则删除DB文件，进入主界面会重新下载基础数据
                deleteDbFile();
            }
        } else {
            goToActivity();
        }

        SharedPreferUtil.getInstance().setIntValue(Constants.LOGIN_TYPE, 1);
        //隐藏验证码
        llCaptcha.setVisibility(View.GONE);
        etCaptcha.setText("");
    }

    /**
     * 需要验证码，并且获取验证码图片
     */
    @Override
    public void getCaptchaImage() {
        llCaptcha.setVisibility(View.VISIBLE);
        setCaptcha();
    }

    /**
     * 加载验证码
     */
    private void setCaptcha() {
        OkHttpUtils
                .get()
                .url(Constants.URL_GET_CAPTCHA_IMAGE)
                .build()
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        showToast("验证码获取失败");
                    }

                    @Override
                    public void onResponse(Bitmap bitmap, int id) {
                        ivCaptcha.setImageBitmap(bitmap);
                    }

                    @Override
                    public Bitmap parseNetworkResponse(Response response, int id) throws Exception {

                        Headers headers = response.headers();
                        List<String> Cookies = headers.values("Set-Cookie");
                        for (int i = 0; i < Cookies.size(); i++) {
                            String Cookie = Cookies.get(i);
                            boolean vcode = Cookie.contains("VCODE");
                            if (vcode) {
                                sharedPreferUtil.setValue(Common.VCODE, Cookie);
                                break;
                            }

                        }
                        return super.parseNetworkResponse(response, id);
                    }
                });
    }

    /**
     * 不需要验证码
     */
    @Override
    public void noNeedCaptchaImage() {
        llCaptcha.setVisibility(View.GONE);
    }

    /**
     * 获取公司名称集合
     *
     * @param data 公司集合
     */
    @Override
    public void getCompanyInfoSuccess(List<CompanyFindAllInfo> data) {
        if (data != null) {
            selectCompany(data);
        } else {
            showToast("查询企业名称为空！");
        }
    }

    private void goToActivity() {
        //获取设备型号
        String phoneModel = SysInfo.getInstance().getPhoneModel();
        if (phoneModel != null && phoneModel.equals(Common.DEV_MODEL)) {
            //工业级平板设备
            toActivity(BreadCardActivity.class);
        } else {
//            toActivity(MainActivity.class);
            toActivity(NewMainActivity.class);
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            mOldBottom = bottom;
            //设置延迟，解决软键盘弹出后影响用户操作问题
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScrollView.scrollTo(0, mChildLayout.getMeasuredHeight() - mScrollView.getHeight());
                }
            }, 300);
        } else if (mOldBottom != bottom) {
            //软键盘高度发生变化时，重新滚动到底部
            mOldBottom = bottom;
            mScrollView.scrollTo(0, mChildLayout.getMeasuredHeight() - mScrollView.getHeight());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            showExitDialog();
        }
        return false;
    }


    // 在主线程更新UI
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String msg) {
        if ("ronghe".equals(msg)) {
            EditText user = findViewById(R.id.user);
            EditText kuaidiPassword = findViewById(R.id.password);
            if (user != null) {
                empCode.setText(user.getText().toString());
            }
            if (kuaidiPassword != null) {
                password.setText(kuaidiPassword.getText().toString());
            }
            DepartmentTableDao departmentTableDao = new DepartmentTableDao();
            DepartmentTable departmentTable = departmentTableDao.queryDeptByDeptCode(MyAppLication.getGlobalOrgCode());
            if (departmentTable!=null){
                sharedPreferUtil.setCompanyCode(departmentTable.getCompCode());
                checkNetworkTime();
            }
            else{
                ToastUtil.showToast("无对应网点");
            }
        }

    }

    /**
     * 退出密码对话框
     */
    protected void showExitDialog() {
        final ExitDialog exitDialog = new ExitDialog(this);
        exitDialog.setPositiveClickListener(R.drawable.btn_bg_ok_common, "确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String pwd = exitDialog.getmExitPwd().getText().toString().trim();
                if (pwd.equals("159753")) {
                    dialog.dismiss();
                    finish();
                    ActivityStack2.getInstance().exit();
                } else if (pwd.equals("")) {
                    showToast("请输入退出密码！");
                } else {
                    showToast("退出密码不正确！");
                }
            }
        });
        exitDialog.setCanceledOnTouchOutside(false);
        exitDialog.setCancelable(false);
        exitDialog.show();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            remindOfflineModelDialog();
        }
    }

    /**
     * 离线模式提醒对话框
     */
    private void remindOfflineModelDialog() {
        MyDialog dialog = new MyDialog(this);
        dialog.setIcon(R.drawable.alert);
        dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
        dialog.setTitle("提示");
        dialog.setMessage("我们检测到你正在打开离线模式，是否确定该操作？");
        dialog.setPositiveClickListener("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                cbOfflineModel.setChecked(true);
            }
        });
        dialog.setNegativeClickListener(R.drawable.btn_login_selector, "否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                cbOfflineModel.setChecked(false);
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 已存在的zip文件解压获取db文件
     * 否则 从服务端获取zip文件解压获取db文件
     */
    private void getDBFile() {
        LoadUtils.showLoading("资源加载中...",this);
        DbHelper.getInstance(LoginActivity.this).close();
        File dbDir = getExternalFilesDir(DbHelper.DB_FILE_DIR);
        if (dbDir != null) {
            for (File item : dbDir.listFiles()) {
                if (item.exists() && !item.getName().equals(Common.DB_ZIP_FILE)) {
                    item.delete();
                }
            }
            String dbFilePath = dbDir.getPath() + File.separator + Common.DB_ZIP_FILE;
            if (new File(dbFilePath).exists()) {
                //存在zip文件直接解压
                unCompressZip(dbFilePath, dbDir.getPath());
            } else {
                //不存在zip文件，从服务端下载zip文件解压
                queryDBInfo(dbDir.getPath(), Common.DB_ZIP_FILE);
            }
        } else {
            goToActivity();
        }
    }

    /**
     * 查询db信息，获取下载url
     *
     * @param saveDir  zip保存目录
     * @param fileName zip文件名称
     */
    private void queryDBInfo(final String saveDir, final String fileName) {
        LoginUtil.queryDBInfo(this, saveDir, fileName, new UICallBack() {
            @Override
            public void onError(String msg) {
                retryDialog(saveDir, fileName);
            }

            @Override
            public void onSuccess(Object obj) {
                unCompressZip(saveDir + File.separator + fileName, saveDir);
            }
        });
    }

    private void unCompressZip(final String zipFilePath, final String savePath) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                LoadUtils.showLoading("解压中...", LoginActivity.this);
            }
        });
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                //解压加密数据库zip文件
                GzipUtil.uncompressZip4j(zipFilePath, savePath, DbHelper.TABLE_NAME, Common.ZIP_PWD);
                //设置为false，防止主界面弹框下载基础数据
                sharedPreferUtil.setServerIpHaveChanged(false);
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                LoadUtils.hideLoading(LoginActivity.this);
                goToActivity();
            }

            @Override
            public void onError(Throwable throwable) {
                LoadUtils.hideLoading(LoginActivity.this);
                retryDialog(savePath, Common.DB_ZIP_FILE);
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }

    private void retryDialog(final String saveDir, final String fileName) {
        LoginUtil.retryDialog(this, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                queryDBInfo(saveDir, fileName);
            }
        });
    }

    /**
     * 删除DB文件
     */
    private void deleteDbFile() {
        showPgDlg("资源重置中...");
        Observable.create(new Observable.OnSubscribe<Void>() {
            @Override
            public void call(Subscriber<? super Void> subscriber) {
                DbHelper.getInstance(LoginActivity.this).close();
                File mFile = getExternalFilesDir("database");
                String path = mFile.getAbsolutePath() + File.separator;
                File file = new File(path);
                for (File item : file.listFiles()) {
                    if (item.exists() && !item.getName().equals(Common.DB_ZIP_FILE)) {
                        item.delete();
                    }
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<Void>() {
            @Override
            public void onCompleted() {
                dismissPgDlg();
                goToActivity();
            }

            @Override
            public void onError(Throwable throwable) {
                dismissPgDlg();
            }

            @Override
            public void onNext(Void aVoid) {
            }
        });
    }


}
